﻿using System;
using System.Linq.Expressions;
using Dorm.Helpers;
using Dorm.Maps;
using Dorm.QueryObject;

namespace Dorm.Services
{
    class UniqueService
    {
        private DataAccess dataAccess;

        public UniqueService(DataAccess _dataAccess)
        {
            dataAccess = _dataAccess;
        }

        public bool IsUnique<T>(T entity, Expression<Func<T, object>>[] propertiesToCheck)
        {
            var entityInfo = new EntityInfo(entity);
            
            var query = new Query<T>().Count();

            foreach(var propertyToCheck in propertiesToCheck)
            {
                string propertyToCheckName = LambdaParser.GetFieldName<T>(propertyToCheck);
                query.Filter(propertyToCheck).Equals(entityInfo.GetValue(propertyToCheckName));
            }

            query.Filter(typeof(T) + ".ID").NotEquals(entityInfo.ID);

            bool isUnique = Convert.ToInt32(dataAccess.ExecuteScalar(query.ToString())) == 0;

            return isUnique;
        }
    }
}
